import { ElMessage } from 'element-plus'
import { BuildPropType } from 'element-plus/lib/utils'
import { createRouter, createWebHistory, Router, RouteRecordRaw } from "vue-router"

const elMessage: Function = (message: string, type: BuildPropType<StringConstructor, "info" | "success" | "warning" | "error", unknown>) => ElMessage({
  message,
  type
})

const routes: Array<RouteRecordRaw> = [
  {
    path: '/index',
    component: () => import("../pages/Index.vue")
  },
  {
    path: '/login',
    component: () => import("../pages/Login.vue")
  },
]
const router: Router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
	//未登录访问其他页面不允许
  if (window.sessionStorage.getItem("token") == null && to.path.match(/^\/index/)) {
    elMessage("未登录，请先登录", "info")
		next('/login')
	}	
	//已登录则无法访问登录入口
	else if (window.sessionStorage.getItem("token") != null && to.path.match(/^\/login/)) {
    elMessage("已登录，无需重复登录", "info")
		next('/index')
	}
	
  next()
})
export default router